package jijian;

import until.DBUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Random;

// 自定义圆角文本框（可选，用于更精致的样式）
class RoundedTextField extends JTextField {
    private int arcWidth = 15;
    private int arcHeight = 15;

    public RoundedTextField(int columns) {
        super(columns);
        setOpaque(false);
        setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(getBackground());
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), arcWidth, arcHeight);
        super.paintComponent(g2);
        g2.dispose();
    }
}

public class SendExpressPanel extends JPanel {
    private JTextField[] fields = new JTextField[5];
    private JComboBox<String> sizeBox;

    public SendExpressPanel() {
        setLayout(new BorderLayout(0, 20));
        setBackground(new Color(245, 245, 245));

        // 标题部分
        JLabel titleLabel = new JLabel("寄快递服务", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(51, 51, 51));
        add(titleLabel, BorderLayout.NORTH);

        // 表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 15, 8, 15);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = 1;

        String[] labels = {"发件人姓名：", "发件人手机号：", "收件人姓名：", "收件人手机号：", "收件人地址：", "选择柜子大小："};
        for (int i = 0; i < 5; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            JLabel label = new JLabel(labels[i]);
            label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            label.setForeground(new Color(70, 70, 70));
            formPanel.add(label, gbc);

            gbc.gridx = 1;
            fields[i] = new RoundedTextField(20);
            fields[i].setBackground(new Color(255, 255, 255));
            fields[i].setFont(new Font("微软雅黑", Font.PLAIN, 14));
            formPanel.add(fields[i], gbc);
        }

        // 柜子大小选择
        gbc.gridx = 0;
        gbc.gridy = 5;
        JLabel sizeLabel = new JLabel(labels[5]);
        sizeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        sizeLabel.setForeground(new Color(70, 70, 70));
        formPanel.add(sizeLabel, gbc);

        gbc.gridx = 1;
        sizeBox = new JComboBox<>(new String[]{"小柜", "中柜", "大柜"});
        sizeBox.setOpaque(false);
        sizeBox.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        sizeBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                setFont(new Font("微软雅黑", Font.PLAIN, 14));
                setBackground(isSelected ? new Color(230, 230, 230) : new Color(255, 255, 255));
                setForeground(new Color(51, 51, 51));
                return this;
            }
        });
        formPanel.add(sizeBox, gbc);

        // 提交按钮
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton submitBtn = new JButton("提交寄件");
        submitBtn.setFont(new Font("微软雅黑", Font.BOLD, 15));
        submitBtn.setForeground(Color.WHITE);
        submitBtn.setBackground(new Color(39, 174, 96));
        submitBtn.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 30));
        submitBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        submitBtn.addActionListener(e -> handleSubmit());
        formPanel.add(submitBtn, gbc);

        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(30, 50, 30, 50)));
        add(formPanel, BorderLayout.CENTER);
    }

    private void handleSubmit() {
        String senderName = fields[0].getText().trim();
        String senderPhone = fields[1].getText().trim();
        String recipientName = fields[2].getText().trim();
        String recipientPhone = fields[3].getText().trim();
        String address = fields[4].getText().trim();
        String size = sizeBox.getSelectedItem().toString();

        if (senderName.isEmpty() || senderPhone.isEmpty() || recipientName.isEmpty() || recipientPhone.isEmpty() || address.isEmpty()) {
            showTip("请填写完整信息", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 先检查是否有可用柜子
        try (Connection conn = DBUtil.getConnection()) {
            String findLockerSql = "SELECT id FROM lockers WHERE status = '空闲' AND size = ? LIMIT 1";
            PreparedStatement findPs = conn.prepareStatement(findLockerSql);
            findPs.setString(1, size);
            ResultSet rs = findPs.executeQuery();

            if (!rs.next()) {
                showTip("暂无可用柜子！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showTip("查询柜子失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 付款方式选择
        int choice = JOptionPane.showOptionDialog(
                this,
                "请选择付款方式：",
                "付款方式选择",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                new String[]{"到付", "立马支付"},
                "立马支付"
        );

        if (choice == 0) {
            processPayment(senderName, senderPhone, recipientName, recipientPhone, address, size, "到付");
        } else if (choice == 1) {
            showPaymentDialog(senderName, senderPhone, recipientName, recipientPhone, address, size, "已支付");
        }
    }

    private void showPaymentDialog(String senderName, String senderPhone,
                                   String recipientName, String recipientPhone,
                                   String address, String size, String paymentMethod) {
        JDialog dialog = new JDialog((Frame) null, "支付快递费", true);
        // 使用垂直 BoxLayout 布局，让组件垂直排列
        dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
        dialog.setBackground(Color.WHITE);
        dialog.setResizable(false);

        JLabel tipLabel = new JLabel("请使用微信扫描二维码支付快递费", SwingConstants.CENTER);
        tipLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        tipLabel.setForeground(new Color(70, 70, 70));
        // 设置水平居中，添加到对话框
        tipLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        dialog.add(tipLabel);

        // 添加间距
        dialog.add(Box.createVerticalStrut(15));

        ImageIcon qrIcon = new ImageIcon("tupian/qrcode.png");
        // 缩小二维码图片，这里设置为原大小的 0.5 倍，可根据需求调整
        Image img = qrIcon.getImage().getScaledInstance(
                qrIcon.getIconWidth() / 2,
                qrIcon.getIconHeight() / 2,
                Image.SCALE_SMOOTH
        );
        qrIcon = new ImageIcon(img);
        JLabel qrLabel = new JLabel(qrIcon);
        qrLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // 水平居中，添加到对话框
        qrLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        dialog.add(qrLabel);

        // 添加间距
        dialog.add(Box.createVerticalStrut(15));

        JButton confirmBtn = new JButton("已支付");
        confirmBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        confirmBtn.setForeground(Color.WHITE);
        confirmBtn.setBackground(new Color(39, 174, 96));
        confirmBtn.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 30));
        confirmBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        confirmBtn.addActionListener(ev -> {
            dialog.dispose();
            processPayment(senderName, senderPhone, recipientName, recipientPhone, address, size, paymentMethod);
        });
        // 水平居中，添加到对话框
        confirmBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
        dialog.add(confirmBtn);

        // 添加底部间距
        dialog.add(Box.createVerticalStrut(20));

        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    private void processPayment(String senderName, String senderPhone,
                                String recipientName, String recipientPhone,
                                String address, String size, String paymentMethod) {
        String code = generateCode();

        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);
            try {
                String findLockerSql = "SELECT id FROM lockers WHERE status = '空闲' AND size = ? LIMIT 1 FOR UPDATE";
                PreparedStatement findPs = conn.prepareStatement(findLockerSql);
                findPs.setString(1, size);
                ResultSet rs = findPs.executeQuery();

                if (!rs.next()) {
                    conn.rollback();
                    showTip("暂无可用柜子！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                int lockerId = rs.getInt("id");

                String insertSql = "INSERT INTO send_express (sender_name, sender_phone, recipient_name, recipient_phone, recipient_address, size, code, locker_id, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                PreparedStatement ps = conn.prepareStatement(insertSql);
                ps.setString(1, senderName);
                ps.setString(2, senderPhone);
                ps.setString(3, recipientName);
                ps.setString(4, recipientPhone);
                ps.setString(5, address);
                ps.setString(6, size);
                ps.setString(7, code);
                ps.setInt(8, lockerId);
                ps.setString(9, paymentMethod);

                if (ps.executeUpdate() > 0) {
                    String updateSql = "UPDATE lockers SET status = '已占用' WHERE id = ?";
                    PreparedStatement updatePs = conn.prepareStatement(updateSql);
                    updatePs.setInt(1, lockerId);
                    updatePs.executeUpdate();

                    String parcelSql = "INSERT INTO parcels (phone, size, code, locker_id, status, create_time) VALUES (?, ?, ?, ?, ?, NOW())";
                    PreparedStatement parcelPs = conn.prepareStatement(parcelSql);
                    parcelPs.setString(1, recipientPhone);
                    parcelPs.setString(2, size);
                    parcelPs.setString(3, code);
                    parcelPs.setInt(4, lockerId);
                    parcelPs.setString(5, "未寄出");
                    parcelPs.executeUpdate();

                    conn.commit();

                    showTip(String.format("寄件成功！\n取件码：%s\n柜子编号：%d\n付款方式：%s",
                            code, lockerId, paymentMethod), "成功", JOptionPane.INFORMATION_MESSAGE);

                    for (JTextField field : fields) field.setText("");
                }
            } catch (SQLException e) {
                conn.rollback();
                throw e;
            } finally {
                conn.setAutoCommit(true);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showTip("提交失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    // 统一提示方法
    private void showTip(String msg, String title, int type) {
        JOptionPane.showMessageDialog(this, msg, title, type);
    }
}